package nix.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;

import nix.jdbc.TxQueryRunner;

import org.apache.commons.dbutils.QueryRunner;

public class BaseDao<T> {

	private QueryRunner qr = new TxQueryRunner();
	private Class<T> beanClass;

	public BaseDao() {
		// 反射泛型
		this.beanClass = (Class<T>) ((ParameterizedType) this.getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	public void add(T bean) {
		try {
			// 通过反射获得类名或注解表名
			String table = this.beanClass.getAnnotation(Table.class) == null ? this.beanClass
					.getSimpleName() : this.beanClass
					.getAnnotation(Table.class).value();
			// 获得字段
			Field[] fs = this.beanClass.getDeclaredFields();
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			Object[] params = new Object[fs.length];
			for (int i = 0; i < fs.length; i++) {
				// 设置可以操作私有属性
				fs[i].setAccessible(true);
				// 获取属性名（注解字段名）和属性值
				if (fs[i].getAnnotation(ID.class) != null) {
					map.put(fs[i].getAnnotation(ID.class).value(),
							fs[i].get(bean));
				} else if (fs[i].getAnnotation(Column.class) != null) {
					map.put(fs[i].getAnnotation(Column.class).value(),
							fs[i].get(bean));
				} else {
					map.put(fs[i].getName(), fs[i].get(bean));
				}
			}
			// sql语句、参数值
			String sqlFields = "";
			String sqlValues = "";
			int i = 0;
			for (Entry<String, Object> entry : map.entrySet()) {
				sqlFields += entry.getKey();
				sqlValues += "?";
				if (i < map.size() - 1) {
					sqlFields += ", ";
					sqlValues += ", ";
				}
				params[i] = entry.getValue();
				i++;
			}
			String sql = "insert into " + table + " (" + sqlFields
					+ ") values (" + sqlValues + ")";

			// qr.update(sql, params);

			System.out.println(map);
			System.out.println(sql);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public T load(String id) {

		return null;
	}
}
